package it.univaq.disim.mwt.business.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import it.univaq.disim.mwt.business.RegistriDiClasseService;
import it.univaq.disim.mwt.business.model.Classe;
import it.univaq.disim.mwt.business.model.RegistroDiClasse;
import it.univaq.disim.mwt.business.model.TipologiaLaboratorio;

public class JDBCRegistroDiClasseService implements RegistriDiClasseService{
	
	//FUNZIONA
	@Override
	public RegistroDiClasse findRegistroDiClasseByID(Long id) {
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		
		String sql = "select * from registri_di_classe where id = ? ";
		RegistroDiClasse registriDiClasse = null;
		
		try {
			connection = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:XE", "school", "school");
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setLong(1, id);
			preparedStatement.executeQuery();	
			resultSet = preparedStatement.getResultSet();
			resultSet.next();
			
			Long ide = resultSet.getLong("id");
			Long idClasse = resultSet.getLong("id_classe");
			
			JDBCClasseService jdbcClasseService= new JDBCClasseService();
			Classe classe= jdbcClasseService.findClassiById(idClasse);
			
			registriDiClasse = new RegistroDiClasse(id,classe);

			resultSet.close();
			preparedStatement.close();
			connection.close();
			
			return registriDiClasse ;

		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		return null;
	}

	//FUNZIONA
	@Override
	public List<RegistroDiClasse> findAllRegistroDiClasse() {

		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		List<RegistroDiClasse> listRegistri = new ArrayList<RegistroDiClasse>();
		String sql = " select * from registri_di_classe ";
		RegistroDiClasse registriDiClasse = null;
		
		try {
			connection = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:XE", "school", "school");
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.executeQuery();	
			resultSet = preparedStatement.getResultSet();
			
			while(resultSet.next()){
				
				Long ide = resultSet.getLong("id");
				Long idClasse = resultSet.getLong("id_classe");
				
				JDBCClasseService jdbcClasseService= new JDBCClasseService();
				Classe classe= jdbcClasseService.findClassiById(idClasse);
				
				registriDiClasse = new RegistroDiClasse(ide,classe);

				
				listRegistri.add(registriDiClasse);
			}
			
			resultSet.close();
			preparedStatement.close();
			connection.close();
		
			return listRegistri;
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}

		return null;
	
	}

}